class MyBlockingQueue{
    private String[] data = new String[1000];
    private volatile int head = 0;
    private volatile int tail = 0;
    private volatile int size = 0;

    public void put(String elem) throws InterruptedException {
        synchronized (this)
        {
            while (size == data.length)
            {
                //队列满了, 继续插入元素, 就会阻塞
                this.wait();
            }
            //没满, 真正的往里面添加元素
            data[tail] = elem;
            tail++;

            if(tail == data.length) tail = 0;

            size++;

            //这个notify用来唤醒take中的wait
            this.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized (this){
            while (size == 0)
            {
                //队列空了
                this.wait();
            }

            //队列不空救出元素
            String ret = data[head];
            head++;
            if(head == data.length)
            {
                head = 0;
            }
            size--;

            //这个notify用来唤醒put中的wait
            this.notify();
            return ret;
        }
    }
}
public class Demo24 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();

        //消费者
        Thread t1 = new Thread(() -> {
            while (true){
                try {
                    String result = queue.take();
                    System.out.println("消费元素: " + result);
                    Thread.sleep(500);
                }catch (InterruptedException e)
                {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread t2 = new Thread(() -> {
            int num = 1;
            while (true)
            {
                try {
                    queue.put(num + "");
                    System.out.println("生产元素: " + num);
                    num++;
                }catch (InterruptedException e)
                {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();
    }
}
